<?php
// 只支持POST请求，否则返回405错误
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
   header('HTTP/1.1 405 Method Not Allowed');
   return;
}

// 获取请求中的用户输入数据
$userName = isset($_POST['username']) ? htmlspecialchars($_POST['username']) : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$passwordConfirm = isset($_POST['password_confirm']) ? $_POST['password_confirm'] : '';

// 数据验证，以及两次输入的密码是否一致
$hasError = false;
$inputBag = [
   'username' => ''
];
$errorBag = [
   'username' => '',
   'password' => '',
   'password_confirm' => ''
];
if (trim($userName) == '') {
   $hasError = true;
   $errorBag['username'] = '用户名不能为空';
}
if (strlen($password) < 6) {
   $hasError = true;
   $errorBag['password'] = '密码长度必须大于等于6位';
}
if ($password !== $passwordConfirm) {
   $hasError = true;
   $errorBag['password_confirm'] = '两次输入的密码必须一致'; 
}
// 验证用户名是否已经被注册
$sql = 'select id from users where user_name=?';
$data = query($sql, [$userName]);
if (count($data) > 0) {
    $hasError = true;
    $errorBag['username'] = '该用户名已被注册';
}

if (isset($_FILES['avatar'])) {
  $file = $_FILES['avatar'];
  // 校验文件信息
  if (!is_uploaded_file($file['tmp_name']) || $file['error'] != 0) {
    $hasError = true;
    $errorBag['avatar'] = '上传文件发生错误';
  }
  if (!in_array($file['type'], ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'])) {
    $hasError = true;
    $errorBag['avatar'] = '您只能上传jpg,png,gif格式的图片文件';
  }
  if ($file['size'] == 0 || $file['size'] > 5 * 1024 * 1024 ) {
    $hasError = true;
    $errorBag['avatar'] = '只支持5M以内的图片';
  }
  // 生成文件名
  $fileName = 'avatar' . DIRECTORY_SEPARATOR . md5(uniqid() . mt_rand()) . '.' . pathinfo($file['name'])['extension'];
  if (!$hasError) {
    $destination = PUBLIC_DIR . DIRECTORY_SEPARATOR . $fileName;
    move_uploaded_file($file['tmp_name'], $destination);
  }
}

// 如果数据验证出现错误，则把错误包数据存入session，重定向到表单页面
$inputBag['username'] = $userName;
$_SESSION['has_error'] = $hasError;
$_SESSION['input_bag'] = $inputBag;
$_SESSION['error_bag'] = $errorBag;
if ($hasError === true) {
   // 重定向
   header('Location:' . url('register'));
   return;
}

// 验证通过，写入数据库
$password = password_hash($password, PASSWORD_BCRYPT);
$sql = 'insert into users(user_name,password, avatar,register_time) values(?,?,?,now())';
$args = [$userName, $password, $fileName];
if (execute($sql, $args)) {
   header('Location:' . url('signin'));
} else {
   header('Location:' . url('register'));
}
